import { gameController } from "./gameController";
import Shape from "./Shape";
import { sleep } from "./utils/util";

const {ccclass, property} = cc._decorator;

/**
 *  
 * 形状网格里面的方格节点 
 * 消除的时候自己下落
 * 
 * */
@ccclass
export default class ShapeItem extends cc.Component {

    /**
     * 自己根据地图的数据自己下落 消除操作上面的节点下落操作
     * @param  {number} clearRowCount 消除的行的个数
     * @param  {number} minClearRow 消除的行中的最小行数
     * @param  {number} maxClearRow 消除的行中的最大行数
     */
    public async goDown(clearRows: number[],minClearRow: number,maxClearRow: number): Promise<void> {
        const map = gameController.gameMap;
        const numMap = gameController.stopedNodeMap;

        const shapeCompStart = this.node.parent.getComponent(Shape);
        const rowColObjStart = shapeCompStart.getSonsInMap(this.node.uuid);
        const [rowStart,colStart] = [rowColObjStart.row,rowColObjStart.col];

        const downFunc = async (downTimes: number) => {
            for(let i = 0; i < downTimes; i++) {
                const shapeComp = this.node.parent.getComponent(Shape);
                const rowColObj = shapeComp.getSonsInMap(this.node.uuid);
                const {row,col} = rowColObj;
        
                /** 清空旧数据 */
                map[row][col] = null;
                numMap[row][col] = 0;
        
                let targetRow = row + 1;
                // 地图里面的位置
                const targetPos = gameController.getMapLocalPos(targetRow,col);
                const worldPos = gameController.shapeManager.mapRoot.convertToWorldSpaceAR(targetPos);
                const localPos = this.node.parent.convertToNodeSpaceAR(worldPos);
                await sleep(1);
                this.node.setPosition(localPos);
    
                if(!map[targetRow]) {
                    debugger;
                }
        
                /** 重新填充地图数据 */
                map[targetRow][col] = this.node;
                numMap[targetRow][col] = 1;
                shapeComp.setSonsInMap(this.node.uuid,{row: targetRow,col});
            }
        }
        if(rowStart < minClearRow) {
            // 最上面消除行的上面所有节点
            downFunc(clearRows.length);
        } else {
            const downTimes = maxClearRow - rowStart;
            downFunc(downTimes);
        }
    }
    
}
